﻿using System.Web.Mvc;
using BrnMall.Services;
using BrnMall.Web.Framework;
using BrnMall.Web.StoreAdmin.Models;
using BrnMall.Manager.Domain.AddressBook;
using BrnMall.Manager.Manager.AddressBook;
using BrnMall.Core;
using System;
using BrnMall.Manager.Manager.Radar;
using BrnMall.Manager.Manager.WeApp;
using System.Linq;
using System.Collections.Generic;
using BrnMall.Manager.Manager.WeChat;

namespace BrnMall.Web.StoreAdmin.Controllers
{
    /// <summary>
    /// 部门成员控制器
    /// </summary>
    public partial class StaffController : BaseStoreAdminController
    {

        #region 员工管理
        /// <summary>
        /// 部门人员列表
        /// </summary>
        /// <param name="pageSize">每页数</param>
        /// <param name="pageNumber">当前页数</param>
        /// <returns></returns>
        public ActionResult StaffList(int DepartmentId = 0, string NickName = "", int pageSize = 15, int pageNumber = 1)
        {

            List<Staff> StaffList = null;
            if (DepartmentId == 0)
            {
                if (string.IsNullOrEmpty(NickName))
                    StaffList = StaffManager.GetDepartmentById(WorkContext.StoreId, pageNumber, pageSize);
                else
                    StaffList = StaffManager.GetDepartmentByName(NickName, pageNumber, pageSize);
            }
            else
            {
                List<StaffDepartment> sdList = StaffDepartmentManager.GetStaffDepList(pageNumber, pageSize, DepartmentId);
                StaffList = new List<Staff>();
                foreach (StaffDepartment sd in sdList)
                    StaffList.Add(StaffManager.Get(sd.StaffId));
            }

            PageModel pageModel = new PageModel(pageSize, pageNumber, StaffManager.GetRecordCount(WorkContext.StoreId,NickName));

            StaffListModel model = new StaffListModel
            {
                PageModel = pageModel,
                staffList = StaffList,
                depList = DepartmentManager.GetListByAmount(WorkContext.StoreId)
            };
            MallUtils.SetAdminRefererCookie(string.Format("{0}?pageNumber={1}&pageSize={2}&NickName={3}",
                                                          Url.Action("stafflist"),
                                                          pageModel.PageNumber,
                                                          pageModel.PageSize,
                                                          NickName));
            return View(model);
        }


        public ActionResult AddStaff(Staff model)
        {
            if (StaffManager.Add(model))
                return PromptView("添加成功");
            else
                return PromptView("添加失败");
        }


        public ActionResult UpdateStaff(Staff model)
        {
            if (StaffManager.Add(model))
                return PromptView("修改成功");
            else
                return PromptView("修改失败");
        }

        public JsonResult EmployeeList()
        {
            return Json(StaffManager.GetDepartmentById(WorkContext.StoreId, 1, 50), JsonRequestBehavior.AllowGet);
        }


        #endregion

        #region 部门管理

        /// <summary>
        /// 部门列表
        /// </summary>
        public JsonResult DepartmentLists()
        {
            return Json(DepartmentManager.GetLists(WorkContext.StoreId), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 根据店铺号获取部门
        /// </summary>
        /// <param name="StoreId"></param>
        /// <returns></returns>
        public ActionResult DepartmentList(int StoreId)
        {
            var model = DepartmentManager.GetListByAmount(StoreId);
            return View(model);
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult AddDepartment(Department model)
        {
            model.StoreId = WorkContext.StoreId;
            if (DepartmentManager.Add(model) > 0)
                return PromptView("添加成功");
            else
                return PromptView("添加失败");
        }


        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ActionResult UpdateDepartment(int Id, string value)
        {
            if (DepartmentManager.Update(Id, value) > 0)
                return PromptView("修改成功");
            else
                return PromptView("修改失败");
        }

        public ActionResult DeleteDepartment(int Id)
        {
            if (DepartmentManager.Delete(Id) > 0)
                return PromptView("删除成功");
            else
                return PromptView("删除失败");
        }

        #endregion

        #region 员工与部门的关系
        /// <summary>
        /// 添加成员列表
        /// </summary>
        /// <returns></returns>
        public ActionResult AddStaffTemplate() {
            AddStaffTemplateModel model = new AddStaffTemplateModel();
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }

        [HttpPost]
        public ActionResult AddStaffTemplate(AddStaffTemplateModel model) {
            if (ModelState.IsValid) {
                Staff staff = new Staff
                {
                    Uid = 1,
                    StoreId = WorkContext.StoreId,
                    Name = model.Name,
                    Position = model.Position,
                    Phone = model.Phone,
                    Mobile = model.Mobile,
                    DepartmentId = model.DepartmentId,
                    Department = DepartmentManager.GetInfo(Convert.ToInt32(model.DepartmentId.Split(',')[0])).Name
                };
                int InsertId = StaffManager.Add2(staff);
                if (InsertId > 0)
                {

                    //顺便更新下添加的部门名称
                    string[] depId = model.DepartmentId.Split(',');
                    for (int i = 0; i < depId.Length; i++)
                    {
                        StaffDepartmentManager.Add(new StaffDepartment()
                        {
                            StoreId = WorkContext.StoreId,
                            StaffId = InsertId,
                            DepartmentId = Convert.ToInt32(depId[i])
                        });
                    }
                    AddStoreAdminLog("添加部门人员模板");
                    return PromptView("部门人员模板添加成功");
                }
                else {
                    return PromptView("部门人员模板添加失败");
                }
            }
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            return View(model);
        }

        
        public ActionResult EditStaffTemplate(int Id = -1)
        {
            var model = StaffManager.Get(Id);
            List<StaffDepartment> sdList = StaffDepartmentManager.GetListByAmount(model.Id);
            string depIds = string.Empty;
            foreach (StaffDepartment sd in sdList)
                depIds += sd.DepartmentId.ToString()+',';
            if (sdList.Count > 0) depIds.Substring(depIds.Length - 1, 1);
            model.DepartmentId = depIds;
            if (model == null)
                return PromptView("部门人员不存在");
            
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            ViewData["allowImgType"] = BMAConfig.UploadConfig.UploadImgType.Replace(".", "");
            ViewData["maxImgSize"] = BMAConfig.UploadConfig.UploadImgSize;
            return View(model);
        }

        [HttpPost]
        public ActionResult EditStaffTemplates(Staff model)
        {
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            model.StoreId = WorkContext.StoreId;
            if (model.DepartmentId.Length <= 0)
                return PromptView("请选择部门");
            string[] depId = model.DepartmentId.Split(',');
            model.Department = DepartmentManager.GetInfo(Convert.ToInt32(depId[0])).Name;
            int updateresult = StaffManager.Update(model);
            //先删除
            StaffDepartmentManager.DeleteByStaffId(model.Id);
            //再添加
            for (int i = 0; i < depId.Length; i++)
            {
                StaffDepartmentManager.Add(new StaffDepartment()
                {
                    StoreId = WorkContext.StoreId,
                    StaffId = model.Id,
                    DepartmentId = Convert.ToInt32(depId[i])
                });
            }
            if (updateresult > 0)
            {
                AddStoreAdminLog("添加部门人员模板");
                return PromptView("部门人员模板添加成功");
            }
            else
                return PromptView("部门人员模板添加失败");
        }


        public ActionResult DeleteStaffTemplate(string Id) {
            if (StaffManager.DeleteAll(Id))
            {
                AddStoreAdminLog("删除部门人员模板");
                return PromptView("部门人员模板删除成功");
            }
            else
                return PromptView("部门人员模板删除失败");

        }

        /// <summary>
        /// 删除部门人员
        /// </summary>
        public ActionResult DeleteStaffTemplateAll(int[] pidList)
        {
            StaffManager.DeleteAll(CommonHelper.IntArrayToString(pidList));
            //顺便删除部门下的设置
            foreach (int i in pidList)
                StaffDepartmentManager.DeleteByStaffId(i);
            AddStoreAdminLog("删除部门人员");
            return PromptView("部门人员删除成功");
        }
        #endregion
        
        #region 员工授权

        public ActionResult Authorization(string NickName = "", int pageSize = 15, int pageNumber = 1)
        {
            List<Staff> StaffList = null;

            if (string.IsNullOrEmpty(NickName))
                StaffList = StaffManager.GetDepartmentById(WorkContext.StoreId, pageNumber, pageSize);
            else
                StaffList = StaffManager.GetDepartmentByName(NickName, pageNumber, pageSize);


            PageModel pageModel = new PageModel(pageSize, pageNumber, StaffManager.GetRecordCount(WorkContext.StoreId, NickName));

            StaffListModel model = new StaffListModel
            {
                PageModel = pageModel,
                staffList = StaffList,
                depList = DepartmentManager.GetListByAmount(WorkContext.StoreId)
            };
            MallUtils.SetAdminRefererCookie(string.Format("{0}?pageNumber={1}&pageSize={2}&NickName={3}",
                                                          Url.Action("stafflist"),
                                                          pageModel.PageNumber,
                                                          pageModel.PageSize,
                                                          NickName));
            return View(model);
        }

        /// <summary>
        /// 生成名片二维码
        /// </summary>
        /// <param name="staffId"></param>
        /// <returns></returns>
        public ActionResult MackQrCode(int staffId)
        {
            var staff = StaffManager.Get(staffId);
            if (staff == null)
                return PromptView("员工不存在");

            //采用自动打包的默认第一个
            var appList = StoreApplicationManager.GetStoreApplications(WorkContext.StoreId);
            if (appList == null || appList.Count == 0)
                return PromptView("您未创建小程序!");

            //已发布，且已授权
            if (appList.Where(t => t.DevStatus >= 4 && t.AuthorizationId > 0 && t.AppId == 33).Count() < 1)
                return PromptView("未找到已上线的名片的小程序!");

            var app = appList.First(t => t.DevStatus >= 4 && t.AuthorizationId > 0 && t.AppId == 33);

            //名片模板路径
            var path = $"/pages/index/index?id={staffId}&source=1";

            var filename = Business.WxQRCode.GetWxaCodeByStoreAppId(WorkContext.StoreId, path, app.StoreAppId);
            if (string.IsNullOrEmpty(filename))
                PromptView($"获取二维码文件失败!AppId:{app.AppId}");

            var redirectUrl = $"https://static.711688.net.cn/upload/user/{filename}";

            //保存二维码
            StaffManager.UpdpateQrCode(staffId, redirectUrl);

            var obj = new { Code = 0, Message = "", Data = redirectUrl };
            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(obj));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="staffid"></param>
        /// <param name="state"></param>
        /// <param name="mode">0：AI,1：BOSS雷达</param>
        /// <returns></returns>
        public ActionResult SetStaffState(int staffid, int state, int mode = 0)
        {
            if (mode == 0)
            {
                StaffManager.UpdateAiState(staffid, state);
                ////关闭AI销售权限，同时也关闭BOSS权限
                //if (state == 0)
                //    StaffManager.UpdateBossState(staffid, 0);
            }
            else
            {
                StaffManager.UpdateBossState(staffid, state);
            }
            return Content("1");
        }

        #endregion

        #region 企业微信授权
        /// <summary>
        /// 企业微信授权
        /// </summary>
        /// <returns></returns>
        public ActionResult WorkWechat()
        {
            var aiCode = PermanentCodeManager.GetByStoreId(WorkContext.StoreId, "AI销售");
            var bossCode = PermanentCodeManager.GetByStoreId(WorkContext.StoreId, "boss销售");

            var model = new WorkWechatModel()
            {
                CompanyName = aiCode == null ? string.Empty : aiCode.corp_full_name,
                AiState = aiCode == null ? 0 : 1,
                BossState = bossCode == null ? 0 : 1
            };
            return View(model);
        }
        #endregion

        public ActionResult WorkHandOver()
        {
            return View();
        }


        public ActionResult WorkHandOvers(int Frist, int Latter)
        {
            ViewData["referer"] = MallUtils.GetStoreAdminRefererCookie();
            if (Frist == 0 || Latter == 0)
                return PromptView("你选择的人不对");
            else if (Frist == Latter)
                return PromptView("你自己不能分配给自己");
            ClientManager.Update(Frist, Latter, 3);
            ClientFollowManager.Update(Frist, Latter);
            ActionRecordManager.Update(Frist, Latter);
            ClientRelationsManager.Update(Frist, Latter);
            return PromptView("工作交接完成");
        }

    }
}